package open.panxiong.shared.activity.screen

import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavBackStackEntry
import kotlinx.coroutines.delay
import open.panxiong.shared.R
import open.panxiong.shared.activity.MainActivity
import open.panxiong.shared.service.NanohttpdService
import open.panxiong.shared.util.ConfigUtil
import open.panxiong.shared.util.createQRCodeBitmap
import open.panxiong.shared.util.deleteDirectory
import open.panxiong.shared.util.getLocalAllIpV4Address
import open.panxiong.shared.util.openHotspotSettings
import open.panxiong.shared.util.showToast
import kotlin.system.exitProcess

class MainViewModel : ViewModel() {
    val serverPort = mutableIntStateOf(NanohttpdService.SERVER_PORT)
    val serverIpList = mutableStateOf(listOf<String>())
    val serverCompleted = mutableStateOf(false)
    val isOpenClearDialogBox = mutableStateOf(false)
    val isOpenTipDialogBox = mutableStateOf(false)
    val showActionMenuView = mutableStateOf(false)
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(stack: NavBackStackEntry) {
    val context = LocalContext.current
    val vm = viewModel<MainViewModel>()
    val appName = stringResource(R.string.app_name)

    LaunchedEffect(key1 = Unit) {
        vm.serverIpList.value = getLocalAllIpV4Address()
    }

    Box(modifier = Modifier.imePadding()) {
        Scaffold(
            topBar = {
                TopAppBar(
                    title = {
                        Text(text = appName)
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        titleContentColor = Color.White,
                        containerColor = MaterialTheme.colorScheme.primary
                    ),
                    actions = {
                        IconButton(onClick = {
                            vm.showActionMenuView.value = true
                        }) {
                            Icon(
                                imageVector = Icons.Default.MoreVert,
                                contentDescription = "and share",
                                tint = Color.White
                            )
                        }
                    }
                )
            },
            bottomBar = {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 55.dp),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Top,
                ) {
                    Button(
                        modifier = Modifier
                            .fillMaxWidth(0.9f),
                        // shape = RoundedCornerShape(16.dp),
                        onClick = {
                            val intent = Intent(Intent.ACTION_VIEW).apply {
                                data = Uri.parse(MainActivity.currentServerUrl.value)
                            }
                            context.startActivity(intent)
                        },
                        enabled = vm.serverCompleted.value
                    ) {
                        Column(Modifier.align(Alignment.CenterVertically)) {
                            Text(
                                text = "共享文件",
                                fontSize = 16.sp,
                                modifier = Modifier.align(Alignment.CenterHorizontally)
                            )
                            Text(
                                text = "前往文件共享页面，查看与添加共享资源",
                                fontSize = 10.sp,
                                modifier = Modifier.align(Alignment.CenterHorizontally)
                            )
                        }
                    }
                }
            }
        ) { pv ->
            Column(
                modifier = Modifier
                    .padding(pv)
                    .fillMaxSize()
                    .verticalScroll(state = rememberScrollState()),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Top,
            ) {
                if (vm.serverIpList.value.isNotEmpty()) {
                    Text(
                        text = "扫码查看共享文件",
                        modifier = Modifier.padding(top = 16.dp),
                        fontSize = 24.sp
                    )
                    Text(
                        text = "（其他手机扫描二维码查看共享文件,多个IP可以左右滑）",
                        modifier = Modifier.padding(bottom = 2.dp),
                        fontSize = 12.sp
                    )
                    HorizontalPager(
                        state = rememberPagerState(initialPage = 0) { vm.serverIpList.value.size },
                        modifier = Modifier
                            .fillMaxWidth()
                            // .weight(1f)
                            .align(Alignment.CenterHorizontally)
                    ) { index: Int ->
                        MainActivity.currentServerUrl.value =
                            "http://${vm.serverIpList.value[index]}:${vm.serverPort.intValue}/"   //
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.Center,
                            modifier = Modifier.padding(top = 16.dp, bottom = 16.dp)
                        ) {
                            val bitmap = createQRCodeBitmap(MainActivity.currentServerUrl.value!!)
                            if (bitmap != null) {
                                Image(
                                    bitmap = bitmap.asImageBitmap(),
                                    contentDescription = vm.serverIpList.value[index],
                                    contentScale = ContentScale.Fit,
                                    modifier = Modifier.fillMaxWidth()
                                )
                            }
                            Row(
                                horizontalArrangement = Arrangement.Center,
                                verticalAlignment = Alignment.CenterVertically,
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .clickable {
                                        val clipboardManager =
                                            context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                                        val label =
                                            ClipData.newPlainText(
                                                "label",
                                                MainActivity.currentServerUrl.value
                                            )
                                        clipboardManager.setPrimaryClip(label)
                                        showToast(context, "链接已经复制到剪切板")
                                    },
                            ) {
                                Text(
                                    text = MainActivity.currentServerUrl.value!!,
                                    fontSize = 20.sp,
                                    lineHeight = 30.sp,
                                    modifier = Modifier.padding(top = 8.dp)
                                )
                                Icon(
                                    imageVector = Icons.Default.Share,
                                    contentDescription = "and share",
                                    modifier = Modifier.size(25.dp, 25.dp)
                                        .padding(start = 5.dp, top = 6.dp)
                                )
                            }
                        }
                    }
                } else {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .align(Alignment.CenterHorizontally)
                            .padding(all = 16.dp),
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(text = "无法读取到设备网络信息")
                    }
                }
            }
        }

        // 一次性引导提示
        GuidePromptView(vm)
        // 清空
        ClearDialogBox(vm)
        // 弹出菜单
        ActionMenuView(vm)
    }

    MainActivity.nanohttpdServiceState.observe(LocalLifecycleOwner.current) { state ->
        vm.serverCompleted.value = state // 设置按钮可用
    }
}

@Composable
fun ClearDialogBox(vm: MainViewModel) {
    if (vm.isOpenClearDialogBox.value) {
        val context = LocalContext.current
        AlertDialog(
            onDismissRequest = { vm.isOpenClearDialogBox.value = false },
            title = { Text("确认操作", fontSize = 16.sp) },
            text = { Text("会清空之前的全部历史与缓存，你确定吗？", fontSize = 14.sp) },
            confirmButton = {
                Button(onClick = {
                    vm.isOpenClearDialogBox.value = false
                    deleteDirectory(context.cacheDir)
                    showToast(context, "清空完成")
                }) {
                    Text("确认", fontSize = 12.sp)
                }
            },
            dismissButton = {
                Button(onClick = { vm.isOpenClearDialogBox.value = false }) {
                    Text("取消", fontSize = 12.sp)
                }
            }
        )
    }
}

/**
 * 引导提示视图
 */
@Composable
fun GuidePromptView(vm: MainViewModel) {
    val context = LocalContext.current
    val appNameText = stringResource(R.string.app_name)
    val guidePromptText = stringResource(R.string.guide_prompt, appNameText)
    val config = ConfigUtil(context)

    LaunchedEffect(key1 = vm.isOpenTipDialogBox.value) {
        if (!config.getBoolean("showGuidePromptView")) {
            delay(1000)
            vm.isOpenTipDialogBox.value = true
        }
    }

    AnimatedVisibility(
        visible = vm.isOpenTipDialogBox.value,
        enter = EnterTransition.None,
        exit = ExitTransition.None
    ) {
        Box(
            modifier = Modifier
                .imePadding()
                .fillMaxSize()
                .background(Color.Black.copy(alpha = 0.5f))
                .clickable {
                    vm.isOpenTipDialogBox.value = false
                },
            contentAlignment = Alignment.Center
        ) {
            Surface(
                modifier = Modifier
                    .fillMaxWidth(0.9f)
                    .height(300.dp)
                    .align(Alignment.Center)
                    .padding(10.dp),
                shape = RoundedCornerShape(16.dp),
                color = Color.White,
            ) {
                Column(modifier = Modifier.padding(10.dp)) {
                    Text(
                        text = "使用提示",
                        fontSize = 18.sp,
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(40.dp)
                            .align(Alignment.CenterHorizontally)
                    )
                    Text(
                        text = guidePromptText,
                        fontSize = 16.sp,
                        modifier = Modifier.weight(1f)
                    )
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.End
                    ) {
                        Spacer(modifier = Modifier.weight(1.0f))
                        Text("不用我有WiFi",
                            modifier = Modifier
                                .padding(10.dp)
                                .clickable {
                                    config.setBoolean("showGuidePromptView", true)
                                    vm.isOpenTipDialogBox.value = false
                                }
                        )
                        Spacer(modifier = Modifier.width(10.dp))
                        Text(
                            "去打开热点",
                            modifier = Modifier
                                .padding(10.dp)
                                .clickable { openHotspotSettings(context) }
                        )
                    }
                }
            }
        }
    }
}

/**
 * 弹出菜单
 */
@Composable
fun ActionMenuView(vm: MainViewModel) {
    val context = LocalContext.current

    val backgroundColor = remember { mutableStateOf(Color.Transparent) }

    LaunchedEffect(key1 = vm.showActionMenuView.value) {
        if (vm.showActionMenuView.value) {
            delay(300)
            backgroundColor.value = Color.Black.copy(alpha = 0.5f)
        } else {
            backgroundColor.value = Color.Transparent
        }
    }

    AnimatedVisibility(
        visible = vm.showActionMenuView.value,
        enter = slideInVertically() + fadeIn(),
        exit = slideOutVertically() + fadeOut(),
    ) {
        Box(
            modifier = Modifier
                .imePadding()
                .fillMaxSize()
                .background(backgroundColor.value)
                .clickable {
                    vm.showActionMenuView.value = false
                },
            contentAlignment = Alignment.Center
        ) {
            Surface(
                modifier = Modifier
                    .fillMaxWidth(0.9f)
                    .align(Alignment.Center)
                    .padding(10.dp),
                shape = RoundedCornerShape(16.dp),
                color = Color.White,
            ) {
                Column(
                    modifier = Modifier.padding(10.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Button(modifier = Modifier
                        .fillMaxWidth(0.9f)
                        .padding(top = 16.dp, bottom = 10.dp),
                        shape = RoundedCornerShape(16.dp),
                        onClick = {
                            val shareIntent = Intent(Intent.ACTION_SEND)
                            shareIntent.type = "text/plain"
                            shareIntent.putExtra(
                                Intent.EXTRA_TEXT,
                                MainActivity.currentServerUrl.value
                            )
                            context.startActivity(
                                Intent.createChooser(shareIntent, "分享到")
                            )
                        }
                    ) {
                        Column(Modifier.align(Alignment.CenterVertically)) {
                            Text(
                                text = "分享链接",
                                fontSize = 16.sp,
                                modifier = Modifier.align(Alignment.CenterHorizontally)
                            )
                            Text(
                                text = "可以选择微信，发送给你好友打开",
                                fontSize = 10.sp,
                                modifier = Modifier.align(Alignment.CenterHorizontally)
                            )
                        }
                    }

                    Button(modifier = Modifier
                        .fillMaxWidth(0.9f)
                        .padding(top = 16.dp, bottom = 10.dp),
                        shape = RoundedCornerShape(16.dp),
                        onClick = {
                            openHotspotSettings(context)
                        }
                    ) {
                        Column(Modifier.align(Alignment.CenterVertically)) {
                            Text(
                                text = "使用热点",
                                fontSize = 16.sp,
                                modifier = Modifier.align(Alignment.CenterHorizontally)
                            )
                            Text(
                                text = "没有wifi可以打开热点连接，速度更快更稳",
                                fontSize = 10.sp,
                                modifier = Modifier.align(Alignment.CenterHorizontally)
                            )
                        }
                    }

                    Button(modifier = Modifier
                        .fillMaxWidth(0.9f)
                        .padding(top = 10.dp, bottom = 10.dp),
                        shape = RoundedCornerShape(16.dp),
                        onClick = {
                            vm.isOpenClearDialogBox.value = true
                        }
                    ) {
                        Column(Modifier.align(Alignment.CenterVertically)) {
                            Text(
                                text = "清空文件",
                                fontSize = 16.sp,
                                modifier = Modifier.align(Alignment.CenterHorizontally)
                            )
                            Text(
                                text = "过多的缓存会使程序运行变慢",
                                fontSize = 10.sp,
                                modifier = Modifier.align(Alignment.CenterHorizontally)
                            )
                        }
                    }

                    Button(modifier = Modifier
                        .fillMaxWidth(0.9f)
                        .padding(top = 10.dp, bottom = 16.dp),
                        shape = RoundedCornerShape(16.dp),
                        onClick = {
                            if (context is Activity) {
                                context.stopService(
                                    Intent(
                                        context,
                                        NanohttpdService::class.java
                                    )
                                )
                                context.finish()
                                exitProcess(0)
                            }
                        }
                    ) {
                        Column(Modifier.align(Alignment.CenterVertically)) {
                            Text(
                                text = "停止共享",
                                fontSize = 16.sp,
                                modifier = Modifier.align(Alignment.CenterHorizontally)
                            )
                            Text(
                                text = "如果不需要继续共享，点此结束",
                                fontSize = 10.sp,
                                modifier = Modifier.align(Alignment.CenterHorizontally)
                            )
                        }
                    }
                }
            }
        }
    }
}